package SwordFingerOffer;

public class Q35_CopyRandomList {
    //带随机指针的链表的复制

    //先复制再切割
    public Node copyRandomList(Node head) {
        if (head == null){
            return null;
        }
        //一段复制
        Node cur = head;
        Node next = null;
        while (cur != null){
            next = cur.next;
            Node cNode = new Node(cur.val);
            cur.next = cNode;
            cNode.next = next;
            cur = next;
        }
        //二段复制 复制随机指向
        //死循环?
        cur = head;
        next = null;
        while (cur != null){
            next = cur.next.next; //可能 = null
            cur.next.random = cur.random != null ? cur.random.next : null;
            cur = next;
        }


        //最难的点 分割链表 依次断连
        Node copyHead = head.next;
        cur = head;
        Node curCopy = head.next;
        while (cur != null) {
            //原来的最后一个节点指向复制节点 此处会修正为空
            cur.next = cur.next.next;
            cur = cur.next;
            //最后一个复制节点本来后面就指向空 无需修正
            //此处分析临界情况即可
            if (curCopy.next != null) {
                curCopy.next = curCopy.next.next;
                curCopy = curCopy.next;
            }
        }
        return copyHead;
    }

    public static void main(String[] args) {
        Q35_CopyRandomList fun = new Q35_CopyRandomList();
        Node root = new Node(1);
        root.next = new Node(2);
        root.random = root.next;
        root.next.random = root;
        Node ans = fun.copyRandomList(root);
        System.out.println(1);
    }

}
